package com.crm.report.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.crm.custinfo.domain.CustBlackList;
import com.crm.custinfo.domain.CustCommentRecord;
import com.crm.custinfo.domain.CustInfo;
import com.crm.custinfo.service.ICustBlackListService;
import com.crm.custinfo.service.ICustCommentRecordService;
import com.crm.custinfo.service.ICustInfoService;
import com.crm.custinfo.service.impl.UserInfoComm;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.constant.StatusConstant;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Md5Encrypt;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.collections4.MapUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.crm.report.domain.CustVisitRecord;
import com.crm.report.service.ICustVisitRecordService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 来访登记统计Controller
 *
 * @author ruoyi
 * @date 2024-02-25
 */
@RestController
@RequestMapping("/crmsys/visitRecord")
public class CustVisitRecordController extends BaseController {
    @Autowired
    private ICustVisitRecordService custVisitRecordService;

    @Autowired
    private UserInfoComm userInfoComm;
    @Autowired
    private ISysUserService iSysUserService;
    @Autowired
    private ICustBlackListService iCustBlackListService;
    @Autowired
    private ICustInfoService iCustInfoService;
    @Autowired
    private ISysDeptService isysDeptService;
    @Autowired
    private ICustCommentRecordService custCommentRecordService;


    /**
     * 查询来访登记统计列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:list')")
    @GetMapping("/list")
    public TableDataInfo list(CustVisitRecord custVisitRecord) {
        startPage();
        List<CustVisitRecord> list = custVisitRecordService.selectCustVisitRecordList(custVisitRecord);
        return getDataTable(list);
    }

    /**
     * 导出来访登记统计列表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:export')")
    @Log(title = "来访登记统计", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, CustVisitRecord custVisitRecord) {
        List<CustVisitRecord> list = custVisitRecordService.selectCustVisitRecordList(custVisitRecord);
        ExcelUtil<CustVisitRecord> util = new ExcelUtil<CustVisitRecord>(CustVisitRecord.class);
        util.exportExcel(response, list, "来访登记统计数据");
    }

    /**
     * 获取来访登记统计详细信息
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(custVisitRecordService.selectCustVisitRecordById(id));
    }

    /**
     * 新增来访登记统计
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:add')")
    @Log(title = "来访登记统计", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody CustVisitRecord custVisitRecord) {
        return toAjax(custVisitRecordService.insertCustVisitRecord(custVisitRecord));
    }

    /**
     * 修改来访登记统计
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:edit')")
    @Log(title = "来访登记统计", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody CustVisitRecord custVisitRecord) {
        return toAjax(custVisitRecordService.updateCustVisitRecord(custVisitRecord));
    }

    /**
     * 删除来访登记统计
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:remove')")
    @Log(title = "来访登记统计", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(custVisitRecordService.deleteCustVisitRecordByIds(ids));
    }

    /**
     * 查询来访登记统计报表
     */
    @PreAuthorize("@ss.hasPermi('crmsys:visitRecord:list')")
    @GetMapping("/visitStaticList")
    public TableDataInfo visitStaticList(CustVisitRecord custVisitRecord) {
        Map<String, Object> inParams = custVisitRecord.getParams();
        Long deptId = MapUtils.getLongValue(inParams, "deptId", -1L);

        if (deptId == -1L) {
            deptId = getLoginUser().getDeptId();
        }
        List<SysDept> deptList = userInfoComm.getOrgListUnderOrgId(deptId);
        // 仅能处理当前用户有部门管辖权限的数据
        Long[] orgIds = new Long[deptList.size()];
        for (int i = 0; i < deptList.size(); i++) {
            SysDept sysDept = deptList.get(i);
            orgIds[i] = sysDept.getDeptId();
        }
        custVisitRecord.setDeptIds(orgIds);

        List<Map<String, Object>> list = custVisitRecordService.visitStaticList(custVisitRecord);
        return getDataTable(list);
    }

    /**
     * 客户来访登记
     *
     * @param custVisitRecord
     * @return
     */
    @Anonymous
    @PostMapping(value = "/custVisit/tenant/{tenantId}")
    public AjaxResult custVisit(@RequestBody CustVisitRecord custVisitRecord) {
        Map<String, Object> result = new HashMap<String, Object>();

        try {
            SysUser user = iSysUserService.getUseyByphonenumber(custVisitRecord.getEmpMobile());
            if (user == null) {
                result.put("code", "-1");
                result.put("msg", "接待顾问手机号有误");
                return success(result);
            }
            SysDept sysDept = isysDeptService.selectDeptById(user.getDeptId());
            CustBlackList custBlackList = new CustBlackList();
            custBlackList.setMobile(custVisitRecord.getMobile());
            // 校验黑名单用户
            List<CustBlackList> black = iCustBlackListService.selectCustBlackListList(custBlackList);
            if (!black.isEmpty()) {
                result.put("code", "-1");
                result.put("msg", "系统当前拒绝访问");
            }
            //是否已经登记
            CustVisitRecord custVisitRecord1 = new CustVisitRecord();
            custVisitRecord1.setMobile(custVisitRecord.getMobile());
            List<CustVisitRecord> visits = custVisitRecordService.selectCustVisitRecordList(custVisitRecord1);
            for (CustVisitRecord visit : visits) {
                if (DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, new Date()).
                        equals(DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, visit.getCreateTime())))
                {
                    result.put("code", "-1");
                    result.put("msg", "您今日已做来访登记");
                    break;
                }
            }
            if (!result.isEmpty()) {
                return success(result);
            }
            CustInfo custInfo = new CustInfo();
            custInfo.setMobile(custVisitRecord.getMobile());
            List<CustInfo> custInfos = iCustInfoService.selectCustInfoList(custInfo);
            if (!custInfos.isEmpty()) {
                //存在
                custInfo = dealWithExists(custInfo, user, custInfos, sysDept.getCity());
            } else {
                custInfo.setCustName(custVisitRecord.getCustName());
                //不存在
                dealWithNew(custInfo, user, sysDept.getCity(), true);
            }
            // 生成一条新的备注
            CustCommentRecord record = new CustCommentRecord();
            record.setCustId(custInfo.getId());
            record.setEmpId(user.getUserId());
            record.setEmpName(user.getNickName());
            record.setRemark("上门登记");
            record.setType(2L);
            record.setType2(2L);
            record.setCreateTime(new Date());

            custCommentRecordService.insertCustCommentRecord(record);
            // 保存登记来访信息
            CustVisitRecord visit = new CustVisitRecord();
            visit.setCustName(custInfo.getCustName());
            visit.setMobile(custVisitRecord.getMobile());
            visit.setEmpMobile(custVisitRecord.getEmpMobile());
            visit.setEmpName(user.getNickName());
            visit.setCreateTime(new Date());
            visit.setCustId(custInfo.getId());
            custVisitRecordService.insertCustVisitRecord(visit);
            result.put("code", "0");
            result.put("msg", "登记成功");
        } catch (Exception e) {
            logger.error("来访登记异常", e);
            result.put("code", "-1");
            result.put("msg", "来访登记异常");
        }
        return AjaxResult.success(result);
    }

    /**
     * 保存客户信息
     *
     * @param custInfo
     * @param user
     * @param city
     * @param isIntroduce
     * @return
     */
    public CustInfo dealWithNew(CustInfo custInfo, SysUser user, String city, boolean isIntroduce) {
        String logInfo = String.format("......apiVisit客户来访登记成功，并自动分配给%s", user.getNickName());
        custInfo.setEmpId(user.getUserId());
        custInfo.setOrgId(user.getDeptId());
        custInfo.setUserId(user.getUserId());
        custInfo.setAddUserId(user.getUserId());
        custInfo.setDeptId(user.getDeptId());
        custInfo.setDistributeTime(new Date());
        custInfo.setOldDistributeTime(new Date());
        custInfo.setDistributeRemark(String.format("%s来访登记自动分配给%s", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, new Date()), user.getNickName()));
        //custInfo.setRemark("前台扫码;");
        custInfo.setStatus(StatusConstant.CUST_STATUS_VISIT);//状态为已上门
        custInfo.setReDistributeStatus(StatusConstant.DISTRIBUTE_STATUS_YES);// 我的客户池
        custInfo.setApplyTime(new Date());
        custInfo.setRepeatFlag("0");
        custInfo.setCity(city);
        custInfo.setMd5val(Md5Encrypt.md5(custInfo.getMobile()));
        if (isIntroduce) {// 扫码
            custInfo.setStarLevel("6"); // 荐介客户
            custInfo.setChannelSource("wxzjs");//扫码渠道
        } else {
            custInfo.setStarLevel("0");
            custInfo.setChannelSource("wxsm");//来访扫码
        }
        iCustInfoService.insertCustInfo(custInfo);

        iCustInfoService.encryptMobile(custInfo, logger);
        logger.info(logInfo);
        return custInfo;
    }

    /**
     * 扫码生成来访登记记录处理逻辑2
     *
     * @param custInfo
     * @param user
     * @param city
     * @return
     */
    public CustInfo dealWithExists(CustInfo custInfo, SysUser user, List<CustInfo> infos, String city) {
        CustInfo cust = null;
        try {

            // 如果当前分公司有该客户则更新为已上门
            for (int i = 0; i < infos.size(); i++) {
                CustInfo info = infos.get(i);
                if (info.getEmpId() != null && info.getUserId().longValue() == user.getUserId().longValue()) {
                    cust = info;
                    break;
                }
            }
            if (cust == null) {
                cust = infos.get(0);
            }
            if (!StatusConstant.CUST_STATUS_LOAN.equals(cust.getStatus()) && !StatusConstant.CUST_STATUS_SIGNED.equals(cust.getStatus())) {
                cust.setStatus(StatusConstant.CUST_STATUS_VISIT);
            }
            cust.setUpdateTime(new Date());
            cust.setLastRemarkTime(new Date());
            iCustInfoService.updateCustInfo2(cust);
            return cust;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("回访登记异常", e);
        }
        return cust;
    }
}
